package org.uninova.mobis.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.uninova.mobis.api.interfaces.swedish.ResRobotJourneyPlannerInterface;
import org.uninova.mobis.pojos.Coordinate;
import org.uninova.mobis.pojos.ResRobotSegment;
import org.uninova.mobis.utils.GISUtilsImpl;
import org.uninova.mobis.utils.SysUtilsImpl;

/**
 * Servlet implementation class GetResRobotRoutesServlet
 * @author PAF
 */
@WebServlet("/GetResRobotRoutesServlet")
public class GetResRobotRoutesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetResRobotRoutesServlet() {
        super();
        
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response) ;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response) ;
	}
	
	/**
	 * This servlet searches ResRobot router for all currently available routes from origin to destination. 
	 * It constructs the HTML which will enable the user to choose what is the best route for him/her.
	 */
	protected void processRequest(HttpServletRequest request, HttpServletResponse response) {
		String origin = request.getParameter("origin") ;
		String destination = request.getParameter("destination") ;
		String waypoints = request.getParameter("waypoints") ;
		
		// DEPARTURE TIME
		String time = request.getParameter("time") ;
		
		//String carSharing = request.getParameter("carSharing") ;
		
		SysUtilsImpl sysUtils = new SysUtilsImpl() ;
		GISUtilsImpl gisUtils = new GISUtilsImpl() ;
		
		Double originLat, originLng, destLat, destLng ;
		
		Coordinate originCoord = gisUtils.getCoordinateFromString(origin) ;
		originLat = originCoord.lat ;
		originLng = originCoord.lng ;
		
		Coordinate destCoord = gisUtils.getCoordinateFromString(destination) ;
		destLat = destCoord.lat ;
		destLng = destCoord.lng ;
		
		ArrayList<Double> lats = new ArrayList<Double>() ;
		ArrayList<Double> lngs = new ArrayList<Double>() ;
		
		ResRobotJourneyPlannerInterface resRobotInterface = new ResRobotJourneyPlannerInterface() ;
		Coordinate fromCoord, toCoord ;
		JSONObject resObject ;
		HashMap<String, ArrayList<ResRobotSegment>> segmentMap ;
		String motType, resp = "" ;
		int counter, segNum ;
		ArrayList<ResRobotSegment> segList ;
		Iterator<String> iter ;
		Timestamp departureTime = null, arrivalTime = null ;
		HttpSession session = request.getSession() ;
		
		String result = "" ;
		
		lats.add(originLat) ;
		lngs.add(originLng) ;
		
		// HANDLE WAYPOINTS, IF ANY
		if (waypoints != null && !waypoints.equals("") && !waypoints.equals("null")) {
			String[] points = null ;
			if (waypoints.contains("!!"))
				points = waypoints.split("!!") ;
			else {
				points = new String[1] ;
				points[0] = waypoints ;
			}
			
			if (points.length > 0) {
				String point ;
				Coordinate coord ;
				
				for (int i = 0; i < points.length; i++) {
					point = points[i] ;
					coord = gisUtils.getCoordinateFromString(point) ;
					
					lats.add(coord.lat) ;
					lngs.add(coord.lng) ;
				}
			}
		}
		
		lats.add(destLat) ;
		lngs.add(destLng) ;
		resp += "{\"segments\":[" ;
		for (int i = 0; i < lats.size() - 1; i++) {
		
			originLat = lats.get(i) ;
			originLng = lngs.get(i) ;
			
			destLat = lats.get(i + 1) ;
			destLng = lngs.get(i + 1) ;
			
			fromCoord = new Coordinate(originLat, originLng) ;
			toCoord = new Coordinate(destLat, destLng) ;
			
			// GET THE DIFFERENT ROUTES AVAILABLE USING PUBLIC TRANSPORTS 
			
			result = resRobotInterface.search("coords", fromCoord, toCoord, null, null, time, false, 1, null) ;
			resObject = JSONObject.fromObject(result) ;
			
			// SAVE THE RESULTING ROUTES INTO A SESSION VARIABLE, SO IT CAN BE USED BY SERVLET 'GetDirectionsResRobot'
			if (session.getAttribute("resRobotResult") != null) {
				result = session.getAttribute("resRobotResult") + "!!" + result ;
			}
					
			session.setAttribute("resRobotResult", result) ;
			
			segmentMap = resRobotInterface.parseAllSegments(resObject) ;
			iter = segmentMap.keySet().iterator() ;
			resp += "{\"segment\":" + i + ",\"html\":\"" ;
			
			// FOR ALL DIFFERENT ROUTES, PREPARE HTML TO SHOW USER, IN ORDER TO SELECT THE PUBLIC TRANSPORT ROUTE THAT HE/SHE WANTS
			while (iter.hasNext()) {
				segNum = Integer.parseInt(iter.next()) ;
				segList = segmentMap.get(String.valueOf(segNum)) ;
				counter = 0 ;
				for (ResRobotSegment seg : segList) {
					if (counter == 0) {
						resp  += "<div class='segment' id='segment_" + segNum + "' onclick='javascript:getPSVDirections(" + segNum + ");'><p><a href='#'>" ;
						departureTime = seg.getDepartureDateTime() ;
					}
					else {
						resp += "<img id='arrow' src='../images/right_arrow.png' />" ;
					}
					if (counter == segList.size() - 1) {
						arrivalTime = seg.getArrivalDateTime() ;
					}
					motType = seg.getMotType() ;
					switch (motType) {
						case "A": resp += "<img src='https://foursquare.com/img/categories_v2/travel/airport_bg_32.png' />" ; break ;
						case "B": resp += "<img src='https://foursquare.com/img/categories_v2/travel/busstation_bg_32.png' />" ; break ;
						case "D": resp += "<img src='https://foursquare.com/img/categories_v2/travel/busstation_bg_32.png' />" ; break ;
						case "E": resp += "<img src='https://foursquare.com/img/categories_v2/travel/taxi_bg_32.png' />" ; break ;
						case "F": resp += "<img src='https://foursquare.com/img/categories_v2/travel/boat_bg_32.png' />" ; break ;
						case "G": resp += "<img id='walking' src='../images/walking.png' />" ; break ;
						case "J": resp += "<img src='https://foursquare.com/img/categories_v2/travel/trainstation_bg_32.png' />" ; break ;
						case "K": resp += "<img src='https://foursquare.com/img/categories_v2/travel/highway_bg_32.png' />" ; break ;
						case "T": resp += "<img src='https://foursquare.com/img/categories_v2/travel/taxi_bg_32.png' />" ; break ;
						case "U": resp += "<img src='https://foursquare.com/img/categories_v2/travel/lightrail_bg_32.png' />" ; break ;
					}
					counter++ ;
				}
				resp += "</a></p>" ;
				resp += "<p>Departure: " + sysUtils.convertTimestampToString(departureTime, null) + "</p>" ;
				resp += "<p>Arrival: " + sysUtils.convertTimestampToString(arrivalTime, null) + "</p></div>" ;
				time = sysUtils.convertTimestampToString(arrivalTime, "yyyy-MM-dd HH:ss") ;
			}
			
			resp += "\"}," ;
		}
		
		resp = resp.substring(0, resp.lastIndexOf(",")) ;
		resp += "]}" ;
		
		try {
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter out = response.getWriter() ;
			out.println(resp) ;
			out.close() ;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
